from rest_framework.views import APIView
from .models import User
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from .serializers import CreateUserSerializer
from rest_framework.permissions import IsAuthenticated
from .serializers import UserCenterInfoSerializer
from django_redis import get_redis_connection


# Create your views here.
# APIView
# GenericAPIView
# ListAPIView ,CreateAPIView
class RegisterUsernameView(APIView):

    """
    判断用户是否注册

    GET     /users/usernames/(?P<username>\w{5,20})/count/

    POST    序列化器

    我们需要把用户名发送过来, 接收用户,根据用户名进行判断
    用户是否注册


    """

    def get(self,request,username):

        # 通过用户名的个数
        count = User.objects.filter(username=username).count()
        # 组织数据,返回
        context = {
            'count':count,
            'username':username #可选
        }

        return Response(context)


class RegisterMobileView(APIView):
    """
    GET     /users/phones/(?P<mobile>1[345789]\d{9})/count/

    GET     /users/phones/?mobile=xxxxx
    POST    /users/phones/      mobile=xxxxx
    根据用户提交的手机号,判断是否存在该手机号
    """


    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()

        context = {
            'count':count,
            'mobile':mobile     #可选
        }

        return Response(context)

# APIView
# GenericAPIVIew
# lsitAPIView,CreateAPIView

# 数据需要入库 我们选项 CreateAPIView
class CreateUserView(CreateAPIView):
    """
    实现注册功能

    POST            /uesrs/

    1. 我们把用户名,密码,手机号,短信验证码, 是否同意协议 post给我们
    2. 对数据进行验证
    3. 验证之后 数据入库


    需求分析(功能分析[参数 和 功能]) --> 确定HTTP的请求方式 --> 确定视图继承自谁
    """


    serializer_class = CreateUserSerializer



#用户中心 ==个人信息
# APIView
# GenericaAPIView
# ListAPIView,
# class UserCenterInfoView(APIView):
#
#     """
#     GET      /users/infos/
#
#     只有登录用户才可以访问
#     获取用户的信息(制定用户的信息)
#
#     """
#
#     permission_classes = [IsAuthenticated]
#
#
#     def get(self,request):
#
#         serializer = UserCenterInfoSerializer(request.user)
#
#         return Response(serializer.data)

# APIView
# GenericaAPIView
# ListAPIView,RetrieveAPIView

from rest_framework.generics import RetrieveAPIView
class UserCenterInfoView(RetrieveAPIView):

    """
    GET      /users/infos/

    只有登录用户才可以访问
    获取用户的信息(制定用户的信息)

    """

    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    #重写 get_object 返回制定的用户信息
    def get_object(self):

        return self.request.user


# APIView
#GenericAPIView
#UpdateAPIView,
from rest_framework.generics import UpdateAPIView
from .serializers import EmailSerializer

class EmailView(UpdateAPIView):
    """

    1. 当用户点击确定按钮的时候,把 邮箱发送给后台,邮箱需要校验
    2. 更新 用户的 邮箱信息
    3. 发送一个激活邮件(链接)
    4. 激活链接应该如何实现发送
    5. 邮件如何发送(代码怎么实现)
    6. 邮件采用celery异步发送

    """

    permission_classes = [IsAuthenticated]

    serializer_class = EmailSerializer

    def get_object(self):

        return self.request.user


from rest_framework import status

class EmailVerifiView(APIView):

    def get(self,request):

        # 1. 获取激活token,判断token是否存在
        token = request.query_params.get('token')

        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 2.对token进行校验
        # 因为我不需要模型对象,所以把模型中的对象方法改为 类方法,静态方法
        user = User.check_verify_token(token)
        if user is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 3. 改变用户的邮件激活状态
        user.email_active = True
        user.save()

        return Response({'message':'ok'})


#APIView
#GenericAPView

#CreateAPIView
from rest_framework.mixins import CreateModelMixin
from .serializers import UserHistroySerailzer,SKUSerializer
from goods.models import SKU
class UserHistoryView(APIView):

    """
    POST

    1. 必须是登录用户
      2. 对传递的数据进行校验, 将数据保存到redis中
    3. 我们是采用的list保存数据
    4. 首先要去重
    5. 保留5条历史记录

    """

    permission_classes = [IsAuthenticated]

    def post(self,request):

        serialier = UserHistroySerailzer(data=request.data, context={'request': request})
        serialier.is_valid()

        return Response(serialier.data)

    def get(self,request):
        """
        1.必须是登录用户
        2.根据指定用户获取指定的redis数据
        3. 通过序列化器 对数据进行 序列化操作
        4.返回数据
        """

        user = request.user
        redis_conn = get_redis_connection('history')
        sku_id = redis_conn.lrange('history_%s'%user.id,0,5)


        skus = []

        for sku_id in sku_ids:

            sku = SKU.object.get(pk=sku_id)

            skus.append(sku)

            # 3.通过序列化器对数据进行序列化操作
            serializer = SKUSerializer(skus, many=True)
            # 4.返回数据
            return Response(serializer.data)



